# -*- coding: utf-8 -*-
# filename: handle.py

import web
import json
import time
import re
from configcenter import configCenter
class bulletMessage(object):
    def POST(self):
        try:
            web.header("Access-Control-Allow-Origin", "*")
            web.header('content-type','application/json')
            webData = web.input()
            mobile = webData.mobile
            message = webData.message
            pattern1 = re.compile(r'1[0-9]{10}')
            if not message:
                results = {'result':False, 'msg':'弹幕消息不得为空'}
            elif pattern1.match(mobile):
                cc = configCenter()
                config = cc.getConfig()
                host = config.get("global", "ip")
                port = config.get("global", "port")
                user = config.get("global", "user")
                pw = config.get("global", "password")
                database = config.get("global", "database")
                db = web.database(dbn='mysql', host=host, port=int(port), user=user, pw=pw, db=database)
                signs = db.select('sign',where="mobile='"+ mobile +"'")
                if len(signs) > 0 :
                    message = str(message)
                    message =  message.replace("&","")
                    message =  message.replace(">","")
                    message =  message.replace("<","")
                    message =  message.replace("\"","")
                    uptime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                    db.insert('bullet',  mobile=mobile, uptime=uptime, message=message)
                    results = {'result':True,'msg':'发送弹幕成功'}
                else:
                    results = {'result':False, 'msg':'手机号未签到'}
            else:
                results = {'result':False, 'msg':'手机号错误'}
            return json.dumps(results)
        except Exception as e:
            return e.args
